package cli.view;

import java.text.NumberFormat;

public class Formats {

    // 百分比
    public static String percent(Double percent) {
        return String.format("%.0f%%", 100 * percent);
    }

    // 进度条
    public static String progressBar(int totalWidth, double progress) {
        StringBuilder result = new StringBuilder();
        int progressWidth = (int) (progress * totalWidth);
        result.append('[');
        for (int i = 0; i < progressWidth; ++i) {
            result.append('=');
        }
        result.append('>');
        for (int i = progressWidth; i < totalWidth; ++i) {
            result.append(' ');
        }
        result.append(']');
        return result.toString();
    }

    // 数字
    public static String number(long number) {
        return NumberFormat.getInstance().format(number);
    }

    // 字节数量
    public static String memorySize(long size) {
        double coefficient = (double) size;
        int magnitude = 0;
        while (coefficient >= 1024) {
            coefficient /= 1024;
            magnitude++;
        }
        String[] magnitudes = {"B", "KB", "MB", "GB"};
        return String.format("%.2f%s", coefficient, magnitudes[magnitude]);
    }

    // 耗时
    public static String elapsedTime(long seconds) {
        long[] magnitudes = {60, 60, 24, Long.MAX_VALUE};
        String[] names = {"s  ", "min", "h  ", "day"};
        int magnitude = 0;
        double coefficient = (double) seconds;
        while (coefficient >= magnitudes[magnitude]) {
            coefficient /= magnitudes[magnitude];
            magnitude++;
        }
        return String.format("%.1f%s", coefficient, names[magnitude]);
    }
}
